package com.etc.zzsys.listener;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import com.etc.zzsys.entiy.Users;

/**
 * Application Lifecycle Listener implementation class LoginListener
 *
 */
@WebListener
public class LoginListener implements HttpSessionAttributeListener {

	private Map<String, HttpSession> map = new HashMap<String, HttpSession>();

	/**
	 * Default constructor.
	 */
	public LoginListener() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
	 */
	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub

		// 添加session时被调用
		String name = arg0.getName();
		if ("users".equals(name)) {
			Users user = (Users) arg0.getValue();
			if (map.get(user.getUserName()) != null) {
				HttpSession session = map.get(user.getUserName());

				Users oldUser = (Users) session.getAttribute("Users");
				System.out.println("用户" + oldUser + " 将被迫下线！");
				session.removeAttribute("users");
				session.setAttribute("msg", "您的账号已经在其他机器上登录,您被迫下线！");

			}
			map.put(user.getUserName(), arg0.getSession());
		}
	}

	/**
	 * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
	 */
	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub
		// 删除属性前被调用
		String name = arg0.getName();
		if ("users".equals(name)) {
			Users user = (Users) arg0.getValue();
			map.remove(user.getUserName());
			System.out.println("用户" + user + "被注销!");
		}
	}

	/**
	 * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
	 */
	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		// TODO Auto-generated method stub

		// 修改属性时被调用
		String name = arg0.getName();
		if ("users".equals(name)) {
			Users oldUser = (Users) arg0.getValue();
			// 移除旧的登录信息
			map.remove(oldUser.getUserName());
			// 新的登录信息
			Users user = (Users) arg0.getSession().getAttribute("users");
			// 也要检查新的账号是否在别的机器上登录
			if (map.get(user.getUserName()) != null) {
				HttpSession session = map.get(user.getUserName());

				session.removeAttribute("users");
				session.setAttribute("msg", "您的账号已经在其他机器上登录,您被迫下线！");

			}
			map.put(user.getUserName(), arg0.getSession());
		}
	}

}
